package libretto.activity;

import java.util.ArrayList;
import java.util.Iterator;

import libretto.connection.ConnectionManager;
import libretto.connection.Esse3HttpClient;
import libretto.utils.Esame;
import libretto.utils.Utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class Libretto extends ListActivity {

	public static final String TAG = Libretto.class.getName();

	private static final int MENU_MEDIA = R.id.mitem01;
	private static final int MENU_UPDATE = R.id.mitem03;

	private ConnectionManager cm;
	private ArrayList<Esame> esami;
	private int tot_crediti_sost;
	private int tot_esami_sost;

	private ProgressDialog progressDialog;
	private SeparatedListAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		String pkg = getPackageName();
		String page_HTML = intent.getStringExtra(pkg + ".lib");
		init(page_HTML);
	}

	private void init(final String page_HTML) {
		progressDialog = ProgressDialog.show(Libretto.this, "Please wait...",
				"Loading data ...", true);
		cm = ConnectionManager.getInstance();
		if (esami == null) {
			esami = new ArrayList<Esame>();
		} else {
			esami.clear();
		}

		new Thread(new Runnable() {

			@Override
			public void run() {
				retriveData(page_HTML);
				librettoHandler.sendEmptyMessage(2);
			}
		}).start();

	}

	private void retriveData(String page_HTML) {
		if (page_HTML == null) {
			return;
		}

		Esame esa;

		Document jsoupDoc = Jsoup.parse(page_HTML);
		Elements trs = jsoupDoc.select("table.detail_table").select(
				"tr:not(:has(th))");
		for (Element tr : trs) {
			esa = new Esame();
			Elements tds = tr.children();
			try {
				esa.setEsame(tds.get(2).text().split(" - ", 2)[1]);
				esa.setAnno_corso(tds.get(1).text());
				esa.setStato_gif(Esse3HttpClient.AUTH_URI
						+ tds.get(8).select("img").first().attr("src"));
				esa.setAa_freq(tds.get(9).text());
				esa.setPeso_crediti(tds.get(10).text());
				esa.setData_esame(tds.get(11).text());
				esa.setVoto(tds.get(12).text());
				esa.setRic(tds.get(14).text());
				esa.setQ_val(tds.get(15).text());
				esami.add(esa);
			} catch (Exception e) {
				Log.e(TAG, "InitEsami: " + e.getMessage());
			}
		}
	}

	private class SeparatedListAdapter extends ArrayAdapter<Esame> {

		public SeparatedListAdapter(Context context, int textViewResourceId,
				ArrayList<Esame> objects) {
			super(context, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.libretto_item, parent, false);
			}

			final Esame esame = esami.get(position);

			TextView label = (TextView) row.findViewById(R.id.esame);
			label.setText(esame.toString());

			label.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent myIntent = new Intent(Libretto.this,
							DettagliEsame.class);

					String pkg = getPackageName();
					myIntent.putExtra(pkg + ".esame", esame.getEsame());
					myIntent.putExtra(pkg + ".anno_corso",
							esame.getAnno_corso());
					myIntent.putExtra(pkg + ".aa_freq", esame.getAa_freq());
					myIntent.putExtra(pkg + ".peso_crediti",
							esame.getPeso_crediti());
					myIntent.putExtra(pkg + ".data_esame",
							esame.getData_esame());
					myIntent.putExtra(pkg + ".voto", esame.getVoto());
					myIntent.putExtra(pkg + ".ric", esame.getRic());
					myIntent.putExtra(pkg + ".q_val", esame.getQ_val());
					myIntent.putExtra(pkg + ".img", esame.getStato_gif());
					startActivityForResult(myIntent, 1);
				}
			});

			TextView voto = (TextView) row.findViewById(R.id.li_voto);
			voto.setText(esame.getVoto());
			return row;
		}

	}

	private double mediaAritmetica() {
		double somma = 0;
		for (Iterator<Esame> i = esami.iterator(); i.hasNext();) {
			Esame e = i.next();
			if (e.getData_esame() == null || e.getData_esame().equals(""))
				continue;
			try {

				somma += Integer.parseInt(e.getVoto());
			} catch (Exception ex) {
				if (e.getVoto().equals("30L")) {
					somma += 30;
				}
			}
		}
		try {
			return Utils.arrotonda(somma / numeroEsami(), 2);
		} catch (Exception e) {
			return 0;
		}
	}

	private double mediaPonderata() {
		int count = 0;
		double somma = 0;
		int crediti = 0;
		for (Iterator<Esame> i = esami.iterator(); i.hasNext();) {
			Esame e = i.next();
			try {
				crediti = Integer.parseInt(e.getPeso_crediti());
				somma += Integer.parseInt(e.getVoto()) * crediti;
				count += crediti;
			} catch (Exception ex) {
				if (e.getVoto().equals("30L")) {
					somma += 30 * crediti;
					count += crediti;
				}
			}
		}
		try {
			return Utils.arrotonda(somma / count, 2);
		} catch (Exception e) {
			return 0;
		}
	}

	private int numeroEsami() {
		tot_esami_sost = 0;
		tot_crediti_sost = 0;
		int no_media = 0;
		for (Iterator<Esame> i = esami.iterator(); i.hasNext();) {
			Esame e = i.next();
			try {
				Integer.parseInt(e.getVoto());
				tot_esami_sost++;
				if (e.getData_esame() != null)
					tot_crediti_sost += Integer.parseInt(e.getPeso_crediti());
			} catch (Exception ex) {
				if (e.getVoto().equals("30L")) {
					tot_esami_sost++;
					tot_crediti_sost += Integer.parseInt(e.getPeso_crediti());
				}
				if (e.getVoto().equals("APPR") || e.getVoto().equals("IDO")) {
					tot_esami_sost++;
					tot_crediti_sost += Integer.parseInt(e.getPeso_crediti());
					no_media++;
				}
			}
		}
		return tot_esami_sost - no_media;
	}

	/**
	 * 
	 * @param menu
	 * @return
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater mInflater = getMenuInflater();
		mInflater.inflate(R.menu.menu, menu);
		return true;
	}

	/**
	 * 
	 * @param item
	 * @return
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case MENU_MEDIA:
			librettoHandler.sendEmptyMessage(1);
			return true;
		case MENU_UPDATE:
			cm.getEsse3Connection().get(Utils.target_libretto);
			try {
				init(Utils.inputStreamToString(cm.getEsse3Connection()
						.getEntity().getContent()));
			} catch (Exception e) {
				Log.e(TAG, e.getMessage());
			}
			return true;
		default:
			return false;
		}
	}

	// Handler serve per aggiornare la grafica
	private Handler librettoHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Intent intent = new Intent(getApplicationContext(), Medie.class);
				String pkg = getPackageName();

				intent.putExtra(pkg + ".aritm",
						String.valueOf(mediaAritmetica()));
				intent.putExtra(pkg + ".pond", String.valueOf(mediaPonderata()));
				intent.putExtra(pkg + ".num", String.valueOf(numeroEsami()));
				intent.putExtra(pkg + ".crediti",
						String.valueOf(tot_crediti_sost));

				startActivity(intent);
			}
			if (msg.what == 2) {
				adapter = new SeparatedListAdapter(Libretto.this,
						R.layout.libretto_item, esami);
				setListAdapter(adapter);
				progressDialog.dismiss();
			}

			adapter.notifyDataSetChanged();
		}
	};
}
